package work.jame.blog.framework.utils.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import work.jame.blog.configuration.security.LoginUser;
import work.jame.blog.framework.exception.user.UserAuthenticationException;
import work.jame.blog.pojo.User;


import java.util.Objects;

/**
 * SpringSecurity工具类
 *
 * @author Jame!
 * @date 2023/5/11 下午 11:04
 */
public class SpringSecurityUtils {

    //密码加密
    private final static BCryptPasswordEncoder ENCODER = new BCryptPasswordEncoder();

    /**
     * 获取当前登录用户信息
     *
     * @return LoginUser对象
     */
    public static LoginUser getCurrentLoginUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            throw new UserAuthenticationException("获取当前登录用户信息失败");
        }
        return (LoginUser) authentication.getPrincipal();
    }

    /**
     * 获取当前登录的用户id
     *
     * @return 当前登录的用户id
     */
    public static Long getCurrentLoginUserId() {
        LoginUser loginUser = getCurrentLoginUserInfo();
        User user = loginUser.getUser();
        if (Objects.isNull(user)) {
            throw new UserAuthenticationException("获取当前登录用户信息失败");
        }
        return user.getId();
    }


    /**
     * 加密用户密码
     *
     * @param password 未加密的原密码
     * @return 加密后的密码
     */
    public static String encryption(String password) {
        return ENCODER.encode(password);
    }


}
